package geektime.io.nio2.demo;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * 模拟通过walkFileTree的方式查找文件
 */
public class FileSearchExample implements FileVisitor<Path> {
    private final String fileName;
    private final Path startPath;

    public FileSearchExample(String fileName, Path startPath) {
        this.fileName = fileName;
        this.startPath = startPath;
    }

    public static void main(String[] args) throws IOException {
        String tempDir = System.getProperty("java.io.tmpdir");
        Path startPath = Paths.get(tempDir);
        FileSearchExample fileSearchExample = new FileSearchExample("temp.txt", startPath);
        Files.walkFileTree(startPath, fileSearchExample);
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        // 如果找完所有的目录都没有发现名字叫fileName的文件，那么最终的这个dir就是startPath
        boolean finishedSearch = Files.isSameFile(dir, startPath);
        if (finishedSearch) {
            System.out.println("File: " + fileName + " not found");
            return FileVisitResult.TERMINATE;
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        String theFileName = file.getFileName().toString();
        if (theFileName.equals(fileName)) {
            System.out.println("Found the file: " + file.toString());
            return FileVisitResult.TERMINATE;
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        System.out.println("Failed to access file: " + file.toString());
        return FileVisitResult.TERMINATE;
    }
}
